package com.feng.gaoerfu.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.feng.gaoerfu.R;
import com.feng.gaoerfu.adapter.MyBallFriendListAdapter;
import com.feng.gaoerfu.base.BaseActivity;
import com.feng.gaoerfu.base.Constants;
import com.feng.gaoerfu.bean.BallPersonData;
import com.feng.gaoerfu.utils.StringUtils;
import com.feng.gaoerfu.view.framework.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;

import static com.feng.gaoerfu.activity.ScoringNowActivity.COME_FROM_SCORING;

/**
 * @time 2017/9/8 0008 12:30
 */

public class MyBallFriendActivity extends BaseActivity {

    private static final int REQUEST_PERSON = 1002;
    @InjectView(R.id.tv_back)
    TextView mTvBack;
    @InjectView(R.id.tv_title)
    TextView mTvTitle;
    @InjectView(R.id.iv_menu)
    ImageView mIvMenu;
    @InjectView(R.id.iv_phone_contact)
    ImageView mIvPhoneContact;
    @InjectView(R.id.layout_add_from_phone)
    RelativeLayout mLayoutAddFromPhone;
    @InjectView(R.id.iv_Manual)
    ImageView mIvManual;
    @InjectView(R.id.layout_add_hand)
    RelativeLayout mLayoutAddHand;
    @InjectView(R.id.my_friend_recycler)
    RecyclerView mMyRecyclerView;
    public static final String TAG = "MyBallFriendActivity";
    @InjectView(R.id.selected_recycler)
    RecyclerView mSelectedRecycler;
    @InjectView(R.id.tv_ensure)
    TextView mTvEnsure;
    private MyBallFriendListAdapter mListAdapter;
    private ArrayList<BallPersonData> mList;

    public int[] icons = {R.drawable.kt_01, R.drawable.kt_02, R.drawable.kt_03, R.drawable.kt_04, R.drawable.kt_05,
            R.drawable.junyong04, R.drawable.kt_06, R.drawable.kt_07, R.drawable.kt_08, R.drawable.kt_09, R.drawable.kt_10
            , R.drawable.kt_11, R.drawable.kt_12};
    private String mListFromScoring;

    @Override
    public int initContentView() {
        return R.layout.activity_ball_friend_contact;
    }

    @Override
    public void initView() {
        mTvTitle.setText("我的球友");
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        mListFromScoring = intent.getStringExtra(COME_FROM_SCORING);

        mMyRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        String stringValue = mSpHelper.getStringValue(Constants.SP_KEY_FRIEND);
        if (TextUtils.isEmpty(stringValue)) {
            mList = new ArrayList<>();
        } else {
            mList = (ArrayList<BallPersonData>) JSONArray.parseArray(stringValue, BallPersonData.class);
            if (!TextUtils.isEmpty(mListFromScoring)) {
                initList(mListFromScoring);
            }
        }

        mListAdapter = new MyBallFriendListAdapter(R.layout.item_my_ball_friend_layout, mList);
        mMyRecyclerView.setAdapter(mListAdapter);
        mListAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                boolean isSelected = mList.get(i).isSelected;

                if (!isSelected && getMaxSelected() >= Constants.MAX_PERSON) {
                    showShortToast("最多选中四个球友!");
                } else {
                    mList.get(i).isSelected = !isSelected;
                    mListAdapter.setNewData(mList);
                    mSelectedAdapter.setNewData(mList);
                }
            }
        });

        mSelectedRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mSelectedRecycler.setAdapter(mSelectedAdapter);
        mSelectedAdapter.setNewData(mList);
    }

    private void initList(String list) {
        //先每个人都不选中
        for (int i = 0; i < mList.size(); i++) {
            mList.get(i).isSelected = false;
        }
        Log.d(TAG, "处理前:mList = " + mList);
        //根据传过来的数据选中相应的人
        List<BallPersonData> ballPersonDatas = JSONArray.parseArray(list, BallPersonData.class);
        for (int i = 0; i < ballPersonDatas.size(); i++) {
            BallPersonData personData = ballPersonDatas.get(i);
            if (personData.type != BallPersonData.ADD) {
                String name = personData.name;
                for (int j = 0; j < mList.size(); j++) {
                    if (mList.get(j).name.equals(name)) {
                        mList.get(j).isSelected = true;
                    }
                }
            }
        }

        Log.d(TAG, "处理后:mList = " + mList);
    }

    private int getMaxSelected() {
        int num = 0;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).isSelected) {
                num++;
            }
        }
        return num;
    }

    BaseQuickAdapter<BallPersonData> mSelectedAdapter = new BaseQuickAdapter<BallPersonData>(R.layout.item_selected_person, mList) {
        @Override
        protected void convert(BaseViewHolder helper, BallPersonData data) {
            helper.setImageResource(R.id.item_select_iv, data.drawable);
            if (data.isSelected) {
                helper.setVisible(R.id.item_select_iv, true);
            } else {
                helper.setVisible(R.id.item_select_iv, false);
            }
        }
    };


    @OnClick({R.id.tv_back, R.id.iv_menu, R.id.layout_add_from_phone, R.id.layout_add_hand, R.id.tv_ensure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.layout_add_from_phone:
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_CONTACTS)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.READ_CONTACTS},
                            Constants.Permission.READ_CONTACTS_REQUEST_CODE);
                    LogUtils.debug(TAG, "沒有权限");
                } else {
                    readContacts();
                    LogUtils.debug(TAG, "请求列表");
                }
                break;
            case R.id.layout_add_hand:
                toActivity(new Intent(mContext, AddFriendActivity.class), REQUEST_PERSON);
                break;
            case R.id.tv_ensure:
                ensure();
                break;
        }
    }

    public static final String COME_FROM_FRIEND = "listFromFriendList";

    private void ensure() {
        ArrayList<BallPersonData> list = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            BallPersonData personData = mList.get(i);
            if (personData.isSelected) {
                list.add(personData);
            }
        }
        Intent intent = new Intent();
        intent.putExtra(COME_FROM_FRIEND, list);
        setResult(RESULT_OK, intent);
        finish();
    }

    private static final int REQUEST_CONTACTS = 10001;

    private void readContacts() {
        showProgressDialog("正在加载中...");
        toActivity(new Intent(mContext, ContactPersonActivity.class), REQUEST_CONTACTS);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constants.Permission.READ_CONTACTS_REQUEST_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    readContacts();
                }
                break;

        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        dismissProgressDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CONTACTS:
                    Log.d(TAG, "onActivityResult 联系人回来");
                    getMobileNo(intent);
                    break;
                case REQUEST_PERSON:
                    BallPersonData personData = intent.getParcelableExtra("person");
                    addNewData(personData);
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void addNewData(BallPersonData personData) {

        if (personData.drawable == 0) {
            int random = StringUtils.random(0, icons.length - 1);
            personData.drawable = icons[random];
        }

        mList.add(personData);
        mListAdapter.setNewData(mList);
        mSelectedAdapter.setNewData(mList);
        storeListToSp(mList);
    }


    /**
     * 获得手机联系人
     *
     * @param intent
     */
    public void getMobileNo(Intent intent) {
        //在返回的方法中处理，获得联系人的信息，姓名，电话，Email,进行相应的处理
        String name = intent.getStringExtra("name");
        boolean hasSamePerson = hasSamePerson(name);
        Log.d(TAG, "getMobileNo hasSamePerson = " + hasSamePerson);
        if (!hasSamePerson) {
            BallPersonData personBean = new BallPersonData();
            personBean.name = name;
            addNewData(personBean);
        } else {
            showShortToast("该球友已在列表中!");
        }
    }

}
